package top.joeallen.rtmptoflv.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @author JoeAllen_Li
 * @Date 2021/3/22 13:33
 * @describe 类描述
 */
public class Cmd {

    public static Cmd getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public int cmd(String[] instruction) {
        String cmd = "nohup ffmpeg  -i "
                + instruction[0] +
                " -f flv -vcodec libx264 -vprofile baseline -acodec aac -f flv  -q 10  rtmp://192.168.1.110:9999/live/"
                + instruction[1]
                + " > /dev/null  & "
//                + " >> /root/java/rtmp/ffmpeg-"
//                + instruction[1]
//                + "-$(date +%Y-%m-%d).log 2>&1"

                ;
        System.out.println(cmd);
        //返回与当前 Java 应用程序相关的运行时对象
        Runtime run = Runtime.getRuntime();

//        if (false) {
//            try {
//                CommandUtil.run(cmd, new File("/"));
//            } catch (IOException e) {
//                e.printStackTrace();
//                return 1;
//            }
//        } else {
        try {
            // 启动另一个进程来执行命令
            Process p = run.exec(cmd);
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
            String lineStr;
            while ((lineStr = inBr.readLine()) != null)
            //获得命令执行后在控制台的输出信息
            {
                // 打印输出信息
                System.out.println(lineStr);
            }
            //检查命令是否执行失败。
            if (p.waitFor() != 0) {
                //p.exitValue()==0表示正常结束，1：非正常结束
                return p.exitValue();
            }
            inBr.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return 1;
        }
//        }
        return 1;
    }

    private static class SingletonHolder {
        private static final Cmd INSTANCE = new Cmd();
    }
}
